package com.demo.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BeanUtil {

    public static Object getFieldValue(Object obj, String fieldName) {
        if (fieldName == null || fieldName.isEmpty()) {
            return null;
        }
        if (!fieldName.contains(".")){
            return getFieldValueSimple(obj, fieldName);
        } else {
            String[] fieldNames = fieldName.split("\\.");
            if (Arrays.stream(fieldNames).anyMatch(StringUtils::isEmpty)) {
                throw new RuntimeException("字段名包含空: " + fieldName);
            }
            Object tmp = obj;
            for (String name : fieldNames) {
                tmp = getFieldValueSimple(tmp, name);
            }
            return tmp;
        }
    }

    private static Object getFieldValueSimple(Object obj, String fieldName) {
        if (obj == null) {
            return null;
        }
        Class<?> clazz = obj.getClass();
        try {
            if (obj instanceof Map) {
                return ((Map<?, ?>) obj).get(fieldName);
            }
            if (NumberUtils.isParsable(fieldName) && obj instanceof List) {
                return ((List<?>) obj).get(Integer.parseInt(fieldName));
            }
            String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method method = clazz.getMethod(methodName);
            return method.invoke(obj);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            // nop
            return null;
        }
    }

}
